package com.nanhang.service.Impl;
import io.seata.spring.annotation.GlobalTransactional;

import cn.hutool.core.util.StrUtil;
import cn.hutool.db.sql.Order;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nanhang.Client.OrderServiceClient;
import com.nanhang.common.util.PageResult;
import com.nanhang.entity.User;
import com.nanhang.mapper.UserMapper;
import com.nanhang.service.UserService;
import com.nanhang.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService{
    @Autowired
    private UserService userService;
    @Autowired
    private OrderServiceClient orderServiceClient;
    // 1. 分页查询
    @Override
    public PageResult<User> findByPage(Integer page, Integer pageSize) {
        Page<User> page1 = this.page(new Page<>(page,pageSize));
        return new PageResult<>(page1.getRecords(),page1.getPages());
    }
    //2,条件分页查询
    @Override
    public PageResult<User> search(Integer page, Integer pageSize, UserVo vo) {

        // 封装查询条件
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(vo.getUname()), "uname",  vo.getUname() );
        // 分页查询
        Page<User> page1 = this.page(new Page<>(page, pageSize), wrapper);
        // 封装分页结果
        return new PageResult<>(page1.getRecords(),page1.getTotal());
    }
    //添加
    @Override
    public boolean add(User user) {
        return this.save(user);
    }
    @GlobalTransactional(name = "create-userandorder", rollbackFor = Exception.class)
    public String addUserWithOrder(User user, Order order) {
        boolean isUserSaved = this.save(user);
        if (!isUserSaved) {return "保存失败";}
        String orderResponse = orderServiceClient.addOrder(order);
        return "用户、订单添加成功:"+ orderResponse;
    }

}
